package com.abaaba.project2.configuration;

import com.aliyun.oss.OSSClient;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
@ConfigurationProperties(prefix = "aliyun")
@Data
public class AliyunComponent {
    private String accessKeyId;
    private String accessKeySecret;
    private Oss oss;
    private Sms sms;

    public OSSClient getOssClient() {
        OSSClient ossClient = new OSSClient(oss.getEndPoint(), accessKeyId, accessKeySecret);
        return ossClient;
    }

    public void fileUpload(String fileName, File file) {
        OSSClient ossClient = getOssClient();
        ossClient.putObject(oss.getBucket(),fileName,file);
    }

    public void sendMsg(String phoneNumber,String code) {
        String signName = sms.getSignName();
        String templateCode = sms.getTemplateCode();

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId","cn-hangzhou");
        request.putQueryParameter("PhoneNumbers",phoneNumber);
        request.putQueryParameter("SignName",signName);
        request.putQueryParameter("TemplateCode",templateCode);
        request.putQueryParameter("TemplateParam","{\"code\":\"" + code + "\"}");

        try {
            CommonResponse commonResponse = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }

    }
}
